package com.xiaojf.xfile.web.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.xiaojf.xfile.service.FileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;

/**
 * 文件上传下载
 *
 * @author Ade.Xiao 2021/4/10 10:28
 */
@Controller
@RequestMapping("/file")
public class FileController {
    private static final Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    @Autowired
    private FileService fileService;

    /**
     * 文件上传
     *
     * @author Ade.Xiao 2021-04-10 11:29:52
     */
    @PostMapping("/upload")
    @ResponseBody
    public String upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file != null || !file.isEmpty()) {
                // 获取文件名
                String fileSuffix = FileUtil.getSuffix(file.getOriginalFilename());
                // 保存文件
                InputStream fileInputStream = file.getInputStream();
                String uri = fileService.storage(fileInputStream, fileSuffix);
                if (StrUtil.isNotBlank(uri)) {
                    return uri;
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
        }

        return "-1";
    }

    @GetMapping("/download")
    public void downLoad(@RequestParam("uri") String uri, HttpServletResponse response) throws IOException {
        File file = fileService.loadFile(uri);

        if (file != null && file.exists()) {
            response.setContentType("application/octet-stream");
            response.setHeader("content-type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(file.getName(), "utf-8"));

            FileUtil.writeToStream(file, response.getOutputStream());
            FileUtil.del(file);
        }
    }
}
